from django.views.generic.simple import direct_to_template
from django.contrib import messages
from filters import AuthenticationFitler
from validationutils import ValidationUtils
from appliance.appliancemanager import ApplianceManager
from appliance.commons import executeCommand
import re, time

@AuthenticationFitler
def pingDevice(request):
    return direct_to_template(request,'utilities/pingDevice.html')

@AuthenticationFitler
def telnetDevice(request):
    return direct_to_template(request,'utilities/telnetDevice.html')

@AuthenticationFitler
def dnslookup(request):
    return direct_to_template(request,'utilities/dnslookup.html')

@AuthenticationFitler
def traceroute(request):
    return direct_to_template(request,'utilities/traceroute.html')

@AuthenticationFitler
def snmplookup(request):
    return direct_to_template(request,'utilities/snmplookup.html')

@AuthenticationFitler
def wmi(request):
    return direct_to_template(request,'utilities/wmitest.html')

@AuthenticationFitler
def ping(request):
    try:
        mylist = []
        utils = ValidationUtils()
        pingInfo = utils.getPingInfo(request)
        errors = utils.isPingInfoValid(pingInfo)
        if errors:
            return direct_to_template(request,'utilities/pingDevice.html',{"errors":errors})
        cmd = "ping -c" + " "+ pingInfo['pkt_count'] + " " + pingInfo['ipaddress']
        status,output = executeCommand(cmd, [], True)
        if status != 0:
            err = "Device is Unreachable"
            packet1 = re.search(r'\d\spackets',output)
            sent = packet1.group()[0]
            packet2 = re.search(r'\d\sreceived',output)
            received = packet2.group()[0]
            perc = re.search(r'\d+%',output)
            lost = perc.group()
            return direct_to_template(request,'utilities/pingDevice.html',{"ipaddress":pingInfo['ipaddress'],"packets":sent,"packet":received,"percent":lost, "err":err})
        ip = output.splitlines()
        expr = "(\d+)\s\S+\s\S+\s(.+):\sicmp_seq=(\d+)\sttl=(\d+)\stime=(\d+.\d+)\sms"
        for line in ip:
            match = re.match(expr, line)
            if match:
                size = match.group(1)
                host = match.group(2)
                icmp = match.group(3)
                ttl = match.group(4)
                rtt = match.group(5)
                a = [size, icmp, ttl, rtt, host]
                mylist.append(a) 
        packet1 = re.search(r'\d+\spackets',output)
        sent = packet1.group()[0]   
        packet2 = re.search(r'\d+\sreceived',output)
        received = packet2.group()[0]
        perc = re.search(r'\d+%',output)
        lost = perc.group()
        max1 = re.search(r'\d+.\d+/\d+.\d+/\d+.\d+/\d+.\d+',output)
        min1 = max1.group()
        res = min1.split('/')
    except Exception, emsg:
        messages.error(request, 'Failed to get ping response - ' + str(emsg))  
    return direct_to_template(request,'utilities/pingDevice.html',{"ipaddress": pingInfo['ipaddress'],"icmp":mylist,"packets":sent,"packet":received,"percent":lost,"max":res[2],"min":res[0],"avg":res[1]})

@AuthenticationFitler
def telnet(request):
    try:
        appmanager = ApplianceManager()
        utils = ValidationUtils()
        telInfo = utils.getTelInfo(request)
        errors = utils.isTelInfoValid(telInfo)
        if errors:
            return direct_to_template(request,'utilities/telnetDevice.html',{"errors":errors})
        str_time = time.time()
        output = appmanager.checkServerConnectivity(telInfo['ipaddress'], telInfo['port'])
        final = time.time() - str_time
        final_time = round(final, 3)
        if not output[0]:
            err = "Failed to connect to " + telInfo['ipaddress'] + " on port " + telInfo['port'] + ". " + str(output[2])
            return direct_to_template(request,'utilities/telnetDevice.html',{"err":err,"ipaddress":telInfo['ipaddress']})
    except Exception, emsg:
        messages.error(request, 'Failed to get telnet response - ' + str(emsg))
    return direct_to_template(request,'utilities/telnetDevice.html',{"results":final_time,"results1":len(output[1]),"results2":output[1],"ipaddress":telInfo['ipaddress']})

@AuthenticationFitler
def dnslook(request):
    try:
        utils = ValidationUtils()
        dnsInfo = utils.getDnsInfo(request)
        errors = utils.isDnsInfoValid(dnsInfo)
        if errors: 
            return direct_to_template(request, 'utilities/dnslookup.html',{"errors":errors})
        cmd = "nslookup" + " " + dnsInfo['ipaddress']
        output = executeCommand(cmd, [], True)[1]
        output1 = re.split(r'\n',output)
        server1 = output1[0].split(':')
        server2 = output1[1].split(':')
        note = output1[3]
    except Exception, emsg:
        messages.error(request, 'Failed to get dnslookup - ' + str(emsg))
    return direct_to_template(request,'utilities/dnslookup.html',{"ipaddress":dnsInfo['ipaddress'],"results":server1[1],"results1":server2[1],"note":note,"original":output1})

@AuthenticationFitler
def traceDevice(request):
    try:
        ipadds = []
        utils = ValidationUtils()
        traceInfo = utils.getTraceInfo(request)
        errors = utils.isTraceInfoValid(traceInfo)
        if errors:
            return direct_to_template(request,'utilities/traceroute.html',{"errors":errors})
        cmd = "traceroute" + " " + traceInfo['ipaddress']
        output = executeCommand(cmd, [], True) [1]
        trac = output.split('\n')
        l = len(trac)
        for i in range(1,l):
            res = re.split(r'\s+',trac[i])
            ipadds.append(res)
            if i >= 9:
                break
    except Exception, emsg:
        messages.error(request, 'Failed to get trace route response - ' + str(emsg))
    return direct_to_template(request,'utilities/traceroute.html',{"results":ipadds,"ipaddress":traceInfo['ipaddress']})

@AuthenticationFitler
def snmpwalk(request):
    try:
        utils = ValidationUtils()
        snmpInfo = utils.getSnmpInfo(request)
        errors = utils.isSnmpInfoValid(snmpInfo)
        if errors:
            return direct_to_template(request,'utilities/snmplookup.html',{"errors":errors})
        if snmpInfo['version'] == "v1":
            cmd = "snmpwalk" + " " + "-"+snmpInfo['version'] + " " + "-c" + " " + snmpInfo['community'] + " " + snmpInfo['ipaddress']+":"+ snmpInfo['port'] + " " + snmpInfo['oid']
        else:
            cmd = "snmpwalk" + " " + "-"+snmpInfo['version'] +"c" + " " + "-c" + " " + snmpInfo['community'] + " " + snmpInfo['ipaddress']+":"+ snmpInfo['port'] + " " + snmpInfo['oid']
        status,output = executeCommand(cmd, [], True)
        if status == 0:
            conn = "snmpSupported"
        else:
            conn = "snmp not supported"
    except Exception, emsg:
        messages.error(request, 'Failed to get SNMP response - ' + str(emsg))
    return direct_to_template(request,'utilities/snmplookup.html',{"ipaddress":snmpInfo['ipaddress'],"results":output,"status":conn}) 

@AuthenticationFitler
def routetable(request):
    try:
        mylist = []
        cmd = "route" + " " + "-n"
        output = executeCommand(cmd, [], True)[1]
        route = output.split('\n')
        l = len(route)    
        for i in range(2,l):
            ip_time = re.split(r'\s+',route[i])
            mylist.append(ip_time)
    except Exception, emsg:
        messages.error(request, 'Failed to get route info - ' + str(emsg))
    return direct_to_template(request,'utilities/routetable.html',{"results": mylist})
